from rest_framework.views import exception_handler
from rest_framework.views import Response
from utils.logging import logger


def common_exception_handler(exc, context):
    res = exception_handler(exc, context)
    # 也可以记录当前登录用户 context['request'].user
    path = context['request'].get_full_path()
    view_name = str(context['view'])
    logger.error('系统错误：请求地址是：%s，请求的试图类是：%s,错误原因是：%s' % (path, view_name, str(exc)))
    if res is not None:
        if res.data.get('detail'):
            if res.data.get('detail').code:
                code = res.data.get('detail').code
            else:
                code = 1404
            msg = res.data.get('detail')
        else:
            code = 1404
            msg = ''
            for k, v in res.data.items():
                for i in v:
                    msg += k
                    msg += i
        if not msg:
            msg = '服务器异常，请联系管理员！'
        return Response({'code': code, 'msg': msg})
    else:
        return Response({'code': 2404, 'msg': '服务器异常，请联系管理员！'})
